package com.blog.controller.admin;

import com.blog.service.UserService;
import com.blog.model.User;
import com.blog.utils.JsonResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private UserService userService;


    @GetMapping("/login")
    public String login(HttpServletResponse response,HttpServletRequest request){
        if(userService.checkStatu(request,response)){
            return "redirect:/admin/";
        }
        return "admin/login";
    }

    @ResponseBody
    @PostMapping("/check")
    public JsonResult loginCheck( HttpServletResponse response, String username, String password){
        try {
            User user = userService.checkLogin(response,username, password);
            return JsonResult.ok();
        } catch (Exception e){
             return JsonResult.fail(e.getMessage());
        }
    }

    @RequestMapping("/logout")
    public String logout(HttpServletResponse response,HttpServletRequest request){
        boolean flag = userService.logout(request,response);
        return "redirect:/auth/login";
    }


//
//    @RequestMapping(value = {"/login"}, method = RequestMethod.GET)
//    public String login2() {
//
//        return "admin/login";
//    }
//
//    @ResponseBody
//    @RequestMapping(value = {"/check"}, method = RequestMethod.POST)
//    public JsonResult login(@RequestParam("username") String username,
//                        @RequestParam("password") String password, ModelMap model
//    ) {
//        try {
//            Subject subject = SecurityUtils.getSubject();
//            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
//            subject.login(token);
//            return JsonResult.ok();
//        } catch (AuthenticationException e) {
//            model.put("message", e.getMessage());
//            System.out.println(e.getMessage());
//        }
//        return JsonResult.ok();
//    }
}
